#include <Windows.h>
#include <Python.h>

#import "C:\\Program Files (x86)\\Common Files\\Intuit\\QBPOSSDKRuntime\\QBPOSXMLRPLib.dll"

int WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{

	switch(fdwReason)
    { 
		case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
			CoInitialize(0);
			break;
        case DLL_THREAD_DETACH:
			CoUninitialize();
			break;
    }

    return TRUE;
}

struct _CTX {
	QBPOSXMLRPLib::IRequestProcessorPtr req;
	_bstr_t ticket;
};

void CloseConnection(PyObject *cap)
{
	_CTX *ctx = (_CTX *)PyCapsule_GetPointer(cap, 0);
	ctx->req->EndSession(ctx->ticket);
	ctx->req->CloseConnection();
	ctx->req.Release();
	delete ctx;
}

static PyObject *OpenConnection(PyObject *self, PyObject *args)
{
	char *computer_name, *company_file, *file_version;
	char buf[1024];
	
	if(!PyArg_ParseTuple(args, "sss", &computer_name, &company_file, &file_version)) return NULL;
	sprintf_s(buf, sizeof(buf) / sizeof(buf[0]), "Computer Name=%s;Company Data=%s;Version=%s", computer_name, company_file, file_version);

	_CTX *ctx = new _CTX();
	ctx->req.CreateInstance(__uuidof(QBPOSXMLRPLib::RequestProcessor));
	ctx->req->OpenConnection("PyQBPOS", "PyQBPOS");
	ctx->ticket = ctx->req->BeginSession(buf);

	return PyCapsule_New(ctx, 0, CloseConnection);
}

static PyObject *ProcessRequest(PyObject *self, PyObject *args)
{
	wchar_t *buf;
	PyObject *obj;
	if(!PyArg_ParseTuple(args, "Ou", &obj, &buf)) return NULL;

	_CTX *ctx = (_CTX *)PyCapsule_GetPointer(obj, 0);
	_bstr_t res = ctx->req->ProcessRequest(ctx->ticket, buf);

	buf = (wchar_t*)res;
	return PyUnicode_FromWideChar(buf, wcslen(buf));
}

static PyMethodDef methods[] = {
    {"OpenConnection",  OpenConnection, METH_VARARGS, "OpenConnection(computer_name, company_file, file_version)"},
	{"ProcessRequest",  ProcessRequest, METH_VARARGS, "ProcessRequest(conn, input)"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC initQBPOS()
{
	Py_InitModule("QBPOS", methods);
}





